package cn.itcast.netty.c3;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class EventLoopServer {
    public static void main(String[] args) {
        AtomicInteger index = new AtomicInteger();
        // 细分 如果遇到一些耗时较长的操作 可以 创建一个独立的eventLoopGroup来专门执行耗时较长的操作
        EventLoopGroup group = new DefaultEventLoopGroup();
        new ServerBootstrap()
                .group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast("handler1",new ChannelInboundHandlerAdapter(){
                            @Override                                           //byteBuf类型
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.debug("handle1---->{}",buf.toString(StandardCharsets.UTF_8));
                                //调用下一个addLast执行
                                if(index.getAndIncrement() % 2 == 0){
                                    ctx.fireChannelRead(msg);
                                }
                            }
                        }).addLast(group,"handler2",new ChannelInboundHandlerAdapter(){
                            @Override                                           //byteBuf类型
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.debug("handle2---->{}",buf.toString(StandardCharsets.UTF_8));
                                ctx.fireChannelRead(msg);
                            }
                        });
//                        ch.pipeline().addLast("handle3",new ChannelInboundHandlerAdapter(){
//                            @Override
//                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                                ByteBuf buf = (ByteBuf) msg;
//                                log.debug("handle3---->{}",buf.toString(StandardCharsets.UTF_8));
//                            }
//                        });
                    }
                })
                .bind(8080);
    }
}
